package historyImport

import (
	"bufio"
	"database/sql"
	"fmt"
	"github.com/henrylee2cn/mahonia"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strings"
	"finance/db"
)

func ImportHistory(code string, starttime string, endtime string) (insertCount int64, failCount int64) {



	resp, _ := http.Get("http://quotes.money.163.com/service/chddata.html?code=" + code + "&start=" + starttime + "&end=" + endtime + "&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;VOTURNOVER;VATURNOVER")

	defer resp.Body.Close() //go的特殊语法，main函数执行结束前会执行resp.Body.Close()

	fmt.Println(resp.StatusCode)          //有http的响应码输出
	if resp.StatusCode == http.StatusOK { //如果响应码为200
		body, err := ioutil.ReadAll(resp.Body) //把响应的body读出
		if err != nil {                        //如果有异常
			fmt.Println(err) //把异常打印
			log.Fatal(err)   //日志
		}
		db:=db.InitMysqlDb()
		insertCount, failCount = readString(strings.Split(string(body), "\n"),db)
		defer  db.Close()
	}
	return
}

//http://quotes.money.163.com/trade/lsjysj_zhishu_000001.html
//http://quotes.money.163.com/service/chddata.html?code=0000852&start=20050104&end=20181031&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;VOTURNOVER;VATURNOVER
//http://quotes.money.163.com/service/chddata.html?code=0000001&start=20050104&end=20181029&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;VOTURNOVER;VATURNOVER
//http://quotes.money.163.com/service/chddata.html?code=0000300&start=20050104&end=20181029&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;VOTURNOVER;VATURNOVER
func readString(arr []string, db *sql.DB) (insertCount int64, failCount int64) {

	insertCount = 0
	failCount = 0
	for i, str := range arr {

		if i == 0 {
			continue
		}
		strArr := strings.Split(str, ",")
		if len(strArr) < 2 {
			break
		}
		//fmt.Println(str)
		create_time := strArr[0]
		code := strArr[1]
		name := strArr[2]
		tclose := strArr[3]
		topen := strArr[4]
		high := strArr[5]
		low := strArr[6]
		lclose := strArr[7]
		chg := strArr[8]
		pchg := strArr[9]
		voturnover := strArr[10]
		vaturnover := strArr[11]

		var dec mahonia.Decoder

		dec = mahonia.NewDecoder("gbk")

		if name1, ok := dec.ConvertStringOK(name); ok {
			name = name1
		}
		code = string([]byte(code)[1:])

		_, errI := db.Exec("INSERT IGNORE into fund_index (type, code,`name` ) value ( ?,?,?)", 0, code, name)
		if errI != nil {
			log.Fatal(errI)
		}

		rs, err := db.Exec("INSERT IGNORE into index_value ( `date`, code,tclose, topen, high,low, lclose,chg,pchg, voturnover, vaturnover) value (?,?,?,?,?,?,?,?,?,?,?)", create_time, code, tclose, topen, high, low, lclose, chg, pchg, voturnover, vaturnover)
		if err != nil {
			log.Fatal(err)

		} else {
			id, _ := rs.LastInsertId()
			if id == 0 {
				failCount += 1
			} else {
				insertCount += 1
			}

		}
		//	fmt.Println(rs.LastInsertId())
	}

	return
}
func read(filename string, db *sql.DB) {

	var count int64
	fin, error := os.OpenFile(filename, os.O_RDONLY, 0)
	if error != nil {
		panic(error)
	}
	defer fin.Close()

	sc := bufio.NewScanner(fin)

	for sc.Scan() {
		count++
		if count == 1 {
			continue
		}
		//	fmt.Printf("the line %d: %s\n", count, sc.Text())
		create_time := strings.Split(sc.Text(), ",")[0]
		code := strings.Split(sc.Text(), ",")[1]
		name := strings.Split(sc.Text(), ",")[2]
		tclose := strings.Split(sc.Text(), ",")[3]
		topen := strings.Split(sc.Text(), ",")[4]
		high := strings.Split(sc.Text(), ",")[5]
		low := strings.Split(sc.Text(), ",")[6]
		lclose := strings.Split(sc.Text(), ",")[7]
		chg := strings.Split(sc.Text(), ",")[8]
		pchg := strings.Split(sc.Text(), ",")[9]
		voturnover := strings.Split(sc.Text(), ",")[10]
		vaturnover := strings.Split(sc.Text(), ",")[11]

		//var create_time2,name2 string
		//var code2="000001"

		//	var  tclose2,topen2,high2,low2,lclose2,chg2,pchg2,voturnover2,vaturnover2 float64

		var dec mahonia.Decoder

		dec = mahonia.NewDecoder("gbk")
		/*		if create_time1, ok := dec.ConvertStringOK(create_time); ok {


				create_time2=create_time1

			}*/
		code = string([]byte(code)[1:])
		if name1, ok := dec.ConvertStringOK(name); ok {
			name = name1
		}



		_, errI := db.Exec("INSERT IGNORE into fund_index (type, code,`name` ) value ( ?,?,?)", 0, code, name)
		if errI != nil {
			log.Fatal(errI)
		}

		rs, err := db.Exec("INSERT IGNORE into index_value ( `date`, code,tclose, topen, high,low, lclose,chg,pchg, voturnover, vaturnover) value (?,?,?,?,?,?,?,?,?,?,?)", create_time, code, tclose, topen, high, low, lclose, chg, pchg, voturnover, vaturnover)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(rs.LastInsertId())
	}
	if err := sc.Err(); err != nil {
		fmt.Println("An error has hippened")
	}

}
